package com.whjk.system.biz.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whjk.core.common.api.Result;
import com.whjk.system.biz.service.SysRoleMenuService;
import com.whjk.system.biz.service.SysRoleService;
import com.whjk.system.data.entity.SysRole;
import com.whjk.system.data.entity.SysRoleMenu;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@Api(value = "系统角色", tags = {"系统角色"})
@RestController
@RequestMapping(value = "role")
public class SysRoleController {
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;


    @PostMapping("/page")
    @ApiOperation("分页")
    public Result<Page<SysRole>> page(@RequestBody SysRole pageDto) {
        return Result.ok(sysRoleService.page(new Page<>(pageDto.getCurrent(), pageDto.getSize()),new LambdaUpdateWrapper<SysRole>().eq(SysRole::getDelFlag,0) ));
    }


    @PostMapping("/add")
    @ApiOperation("新增角色")
    public Result addRole(@RequestBody SysRole pageDto) {
        sysRoleService.save(pageDto);
        return Result.ok();
    }


    @PostMapping("/update")
    @ApiOperation("修改角色")
    public Result updateRole(@RequestBody SysRole sysRole) {
        sysRoleService.updateById(sysRole);
        return Result.ok();
    }

    @PostMapping("/menu/update")
    @ApiOperation("修改角色权限")
    public Result menuUpdate(@RequestBody SysRole sysRole) {
        SysRoleMenu roleMenu = new SysRoleMenu();
        roleMenu.setDelFlag("1");
        sysRoleMenuService.update(roleMenu, new LambdaQueryWrapper<SysRoleMenu>()
                .eq(SysRoleMenu::getRoleId, sysRole.getId()));
        List<SysRoleMenu> collect = sysRole.getMenuIds().stream().map(f -> {
            SysRoleMenu roleMenu2 = new SysRoleMenu();
            roleMenu2.setRoleId(sysRole.getId());
            roleMenu2.setMenuId(f);
            return roleMenu2;
        }).collect(Collectors.toList());
        sysRoleMenuService.saveBatch(collect);
        return Result.ok();
    }
}